<template>
  <div>
    <div>
      <ElUpload :before-upload="beforeUpload" :multiple="multiple" :show-file-list="false">
        <ElButton v-if="multiple">文件上传</ElButton>
        <div v-else >
          <ElTag v-if="files.length > 0" closable @close="clear">
            {{ files[0].name }}<span v-show="files[0].percent >= 0 && files[0].percent != 100">({{ files[0].percent }}%)</span>
          </ElTag>
          <ElButton v-else>文件上传</ElButton>
        </div>
      </ElUpload>
      <div v-if="multiple && files.length > 0" class="border border-solid border-blue flex flex-col">
        <ElTag v-for="(file, i) in files" :key="i" closable @close="files.splice(i, 1)" class="mt1 mb1">
          {{ file.name }}<span v-show="file.percent >= 0 && file.percent != 100">({{ file.percent }}%)</span>
        </ElTag>
        <ElButton v-if="needUpload" @click="upload">上传</ElButton>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ElButton, ElTag, ElUpload } from 'element-plus'
  import { ref, watchEffect, computed } from 'vue'
  import { useUploader } from '@/hooks/web/useUploader'
  import { getRealName } from '@/utils/fileUtil'
  import VueTypes from 'vue-types'

  const props = defineProps({
    bucket: VueTypes.string.isRequired,
    path: VueTypes.string.def(''),
    multiple: VueTypes.bool.def(false),
    modelValue: VueTypes.string.def('')
  })

  const emit = defineEmits(['update:modelValue'])

  const bucket = ref(props.bucket)
  const path = ref(props.path)
  const { files, beforeUpload, upload, clear } = useUploader(bucket, path, props.multiple)

  if(props.modelValue) {
    const items = props.modelValue.split(',')
    for(const i in items) {
      const filePath = items[i]
      files.push({ name: getRealName(filePath), filePath })
    }
  }

  const needUpload = computed(() => {
    for(const i in files) {
      const { filePath } = files[i]
      if(!filePath) return true
    }

    return false
  })

  watchEffect(() => {
    let ret = ''
    for(const i in files) {
      const { filePath } = files[i]
      if(filePath) {
        if(ret) ret += ','
        ret += filePath
      }
    }
    emit('update:modelValue', ret)
  })

</script>